﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AdvCMS.Data.Repositories;
using AdvCMS.Factory;
using System.Web.UI;
using AdvCMS.Data;
using PagedList;

namespace AdvCMS.Controllers
{
    public class PageController : BaseController
    {
        //
        // GET: /Page/
        public IPageRepository PageRepository { get; set; }

        public PageController()
            : base()
        {
            RepositoryFactory factory = new RepositoryFactory();
            PageRepository = factory.NewPageRepository();
        }

        public ActionResult Index(string pageName)
        {
            IAdvPage page =PageRepository.GetPage(pageName);
            ViewData["Title"] = page.PageTitle;
            ViewData["Content"] = page.PageContent;


            return View();
        }
        [Authorize]
        public ActionResult List(int? page)
        {
            IList<IAdvPage> pages = PageRepository.FindAll();

            var pageNumber = page ?? 1;
            var onePageOfPages = pages.ToPagedList(pageNumber, 25);

            ViewBag.OnePageOfPages = onePageOfPages;
            return View();

        }

        [Authorize]
        // https://play.google.com/store/apps/details?id=com.advgen.AdvNetInfoPro - Android Network Tools
        // Edit/Create a page
        public ActionResult EditPage(int? id)
        {
            IAdvPage page = PageRepository.Create();
            if (id.HasValue)
            {
                page = PageRepository.Get(id.Value);
            }

            return View(page);
        }

        [Authorize]
        public ActionResult Delete(int id)
        {
            IAdvPage page = PageRepository.Get(id);
            PageRepository.Delete(page);
            PageRepository.Update();

            TempData["Message"] = "The record is deleted";
            return RedirectToAction("List");
        }


        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        // https://play.google.com/store/apps/details?id=com.advgen.AdvNetInfoPro - Android Network Tools
        // Edit/Create a page
        public ActionResult EditPage(int? id, string pageName, string pageTitle, string pageContent)
        {
            IAdvPage page = PageRepository.Create();
            if (id.HasValue && id != 0)
            {
                page = PageRepository.Get(id.Value);
            }


            page.PageName = pageName;
            page.PageTitle = pageTitle;
            page.PageContent = pageContent;
            if (page.Id == 0)
            {
                PageRepository.Insert(page);
            }
            PageRepository.Update();

            return View(page);
        }
        

    }
}
